package com.mk.sql.contorller;

import com.dot.customize.log.annotation.DotLog;
import com.mk.sql.bean.Strategy;
import com.mk.sql.mapper.StrategyMapper;
import com.mk.sql.service.RExcelService;
import com.mk.sql.util.FileUpload;
import com.mk.sql.util.PathUtil;
import com.mk.sql.util.ReadExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author xuzn @ClassName: RExcelController @ProjectName generator_sql
 * @date 2020/5/20/10:45 下午
 */
@Slf4j
@Controller
@RequestMapping(value = "/excel")
public class RExcelController {

  public static final String FILEPATHFILE = "uploadFiles/file/";

  @Autowired
  private RExcelService rExcelService;

  /**
   * 从EXCEL导入到数据库
   */
  // localhost:8081/excel/readExcel
  @RequestMapping(value = "/readExcel")
  @DotLog(description = "从EXCEL导入到数据库")
  @ResponseBody
  public String readExcel(@RequestParam(value = "excel", required = false) MultipartFile file, @RequestParam(value = "is_auto") boolean isAuto) {
    String ret = "success";
    if (null != file && !file.isEmpty()) {
      // 判断excel文件是03版本还是07版本
      // 文件上传路径
      String filePath = PathUtil.getClasspath() + FILEPATHFILE;
      // 执行上传
      String fileName = FileUpload.fileUp(file, filePath, "excel");
      List<Map<String, Object>> list = ReadExcelUtil.readExcel(filePath, fileName, 1, 0, 0);
      int size = list.size();
      if (size == 0) {
        ret = "list size is 0";
        return ret;
      }
      Date date = new Date();
      DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String dateStr = dateFormat.format(date);
      List<Strategy> strategies = new ArrayList<>();
      int flag = 0;//定义一个标志

      for (int i = 0; i < size; i++) {
        try {
          Object oid = list.get(i).get("var" + 0);
          String id = oid.toString();
          String no = list.get(i).get("var" + 1).toString();
          String desc = list.get(i).get("var" + 2).toString();
          String name = list.get(i).get("var" + 3).toString();
          Object o = list.get(i).get("var" + 4);
          String value = "";
          if (o != null && !"".equals(o)) {
            value = o.toString();
          }
          String type = list.get(i).get("var" + 5).toString();
          String calculate = list.get(i).get("var" + 6).toString();
          if (!isAuto) {
            String str =
                    "INSERT INTO `scdata`.`strategy` ( `pkid`,`id`, `strategy_no`, `channel_id`, `group_no`, `status`, `strategy_name`, `create_time`,"
                            + " `update_time`, `desc`, `direct_key`, `direct_key_type`, `ognl_value`, `strategy_logic`) VALUES "
                            + "( "
                            + no
                            + ", "
                            + no
                            + ",'"
                            + no
                            + "', "
                            + id
                            + ", '1', 1, '"
                            + calculate
                            + "', '"
                            + dateStr
                            + "', '"
                            + dateStr
                            + "', "
                            + "'"
                            + desc
                            + "', '"
                            + name
                            + "', '"
                            + type
                            + "', '"
                            + value
                            + "', '"
                            + desc
                            + "');";
            System.out.println(str);
          } else {

            flag++;
            Strategy strategy = new Strategy();
            strategy.setPkid(Integer.parseInt(no));
            strategy.setId(Integer.parseInt(no));
            strategy.setStrategyNo(no);
            strategy.setChannelId(Integer.parseInt(id));
            strategy.setGroupNo("1");
            strategy.setStatus(1);
            strategy.setStrategyName(calculate);
            strategy.setCreateTime(date);
            strategy.setUpdateTime(date);
            strategy.setDesc(desc);
            strategy.setDirectKey(name);
            strategy.setDirectKeyType(type);
            strategy.setOgnlValue(value);
            strategy.setStrategyLogic(desc);
            strategy.setSample("");
            strategy.setDemander("");
            strategies.add(strategy);
            if (size <= 1) {
              rExcelService.saveStrategies(strategies);
              return "success";
            }
            if (flag == 200) {
              //标识达到 200 进行批量插入操作
              rExcelService.saveStrategies(strategies);
              //操作完成后清空容器
              strategies.clear();
              //将标识重新置位0
              flag = 0;
              //最后的数据不足 200 条则判断数据是否已经是最后一条，如果是，进行批量插入操作
            } else if (i == size - 1) {
              rExcelService.saveStrategies(strategies);
              strategies.clear();
            }
          }
        } catch (Exception e) {
          ret = "fail";
          e.printStackTrace();
          log.info(e.getMessage());
          return ret;
        }
      }
    }
    return ret;
  }
}
